package com.lungle.warmdiary.app.view.me.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.TesterIndustry;
import com.lungle.warmdiary.app.model.response.User;
import com.lungle.warmdiary.app.ui.dialog.CommonDialog;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.me.LoginActivity;
import com.lungle.warmdiary.app.view.me.adapter.PassAdapter2;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * useruser
 * Created by God on 2016/8/25.
 */
public class UserProfileFragment extends BaseFragment {
    private static final String USER_PROFILE_SCREEN = "user profile screen";
    @Bind(R.id.et_username)
    EditText mEtUsername;
    @Bind(R.id.et_cellphone)
    EditText mEtCellphone;
    @Bind(R.id.et_email)
    EditText mEtEmail;
    @Bind(R.id.et_gender)
    EditText mEtGender;
    @Bind(R.id.et_birth)
    EditText mEtBirth;
    @Bind(R.id.et_qq)
    EditText mEtQQ;
    @Bind(R.id.root)
    LinearLayout root;
    @Bind(R.id.industry_images)
    GridView industryImages;
    @Bind(R.id.change_pwd)
    TextView changePwd;
    @Bind(R.id.industry_images_layout)
    LinearLayout industryImagesLayout;
    @Bind(R.id.signout)
    Button signout;

    private User mUser;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        ButterKnife.bind(this, view);
        initData();
        initView(view);
        changePwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UIHelper.showChangePwd(getActivity());
            }
        });

        signout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonDialog dialog = new CommonDialog(getActivity());
                dialog.setMessage("亲，您确定退出此账号？");
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        AppContext.getInstance().Logout();
                        dialog.dismiss();
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        intent.putExtra(LoginActivity.BUNDLE_KEY_REQUEST_CODE, LoginActivity.REQUEST_CODE_RELOGIN);
                        AppContext.getInstance().Logout();
                        getActivity().startActivity(intent);

                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                dialog.show();
            }
        });
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(USER_PROFILE_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(USER_PROFILE_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    @Override
    public void initView(View view) {
        loadUserInfo();
        loadTesterStat();
    }

    @Override
    public void initData() {
        mUser = AppContext.getInstance().getLoginUser();

    }


    private void fillUI() {
        mEtUsername.setText(mUser.getUsername());
        mEtCellphone.setText(mUser.getCellphone());
        mEtEmail.setText(mUser.getEmail());
        if (mUser.getGender() != null)
            mEtGender.setText(mUser.getGender() == User.CODE_FAMALE ? "女" : "男");
        mEtBirth.setText(mUser.getBirthday());
        mEtQQ.setText(mUser.getQq());

        List<Integer> industry = mUser.getIndustry();

        if (industry != null && industry.size() > 0) {
            industryImagesLayout.setVisibility(View.VISIBLE);
            PassAdapter2 passAdapter = new PassAdapter2(getActivity(), industry);
            industryImages.setAdapter(passAdapter);
            passAdapter.notifyDataSetChanged();
        } else {
            industryImagesLayout.setVisibility(View.GONE);
        }


//
//        int n3 = industry.size() / 3 + 1;
//
//
//        for (int i = 0; i < n3 * 3; i++) {
//            if (i >= industry.size())
//                industry.add(-1);
//        }
//
//        int header = industry.get(n3);
//        int tail = industry.get(n3 + 2);
//
//
//        if (industry != null && industry.size() > 0 && industry.size() < 3) {
//
//            for (int i = 0; i < 3; i++) {
//                if (i >= industry.size())
//                    industry.add(-1);
//            }
//        }
//
//        int header = industry.get(0);
//        int tail = industry.get(2);
//
//        industry.set(2, header);
//        industry.set(0, tail);


    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_userprofile;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private void loadUserInfo() {
        showWaitDialog();
        ApiFactory.getUserApi().getUserProfile().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<User>>(getActivity()) {
                    @Override
                    public void onError(Throwable e) {
                        fillUI();
                        hideWaitDialog();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<User> userResult) {
                        User user = userResult.getData();
                        if (user != null) {
                            mUser = user;
                            AppContext.getInstance().saveLoginInfo(mUser);
                        }


                        fillUI();


                    }
                });
    }


    private void loadTesterStat() {
        showWaitDialog();

        Observable<Result<List<TesterIndustry>>> tags;

        tags = ApiFactory.getUserApi().getTesterIndustryList();

        tags.subscribeOn(Schedulers.newThread())
                .compose(this.<Result<List<TesterIndustry>>>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result<List<TesterIndustry>>>() {
                    @Override
                    public void onCompleted() {


                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Result<List<TesterIndustry>> tagResult) {
                        List<TesterIndustry> mTagList = tagResult.getData();
                        AppContext.setIndustryNum(mTagList.size());
                        for (TesterIndustry industry : mTagList) {
                            AppContext.setIndustry(industry.getId(), industry.getIcon(), industry.getName());
                        }
                    }
                });


    }

}


